package com.zjj.lbw.designpattern.prototype.clone;

/**
 * @author zhanglei.zjj
 * @description 克隆之深拷贝
 * @date 2023/7/14 16:04
 */
public class CloneTest2 {
    public static void main(String[] args) throws Exception {
        Teacher teacher = new Teacher();
        teacher.setAge(40);
        teacher.setName("teacher zhang");

        Student2 student1 = new Student2();
        student1.setAge(23);
        student1.setName("zjj");
        student1.setTeacher(teacher);

        Student2 student2 = (Student2) student1.clone();

        System.out.println(student2.getAge());
        System.out.println(student2.getName());
        System.out.println(student2.getTeacher().getAge());

        // 修改原来teacher的name属性，不会彼此发生影响
        teacher.setName("teacher li");
        System.out.println(student2.getTeacher().getName());

    }
}

class Student2 implements Cloneable {
    private int age;
    private String name;
    private Teacher teacher;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Teacher getTeacher() {
        return teacher;
    }

    public void setTeacher(Teacher teacher) {
        this.teacher = teacher;
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        // 这一步返回的这个student2还只是一个浅克隆，
        Student2 student2 = (Student2) super.clone();
        student2.setTeacher((Teacher) student2.getTeacher().clone());
        return student2;
    }
}

class Teacher implements Cloneable {
    private int age;
    private String name;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

}

